const express = require('express')
const router = express.Router()
const db = require('../../../MySql')
const { generate19DigitId } = require('../../utils/idUtils')


router.post('/repo/save', async (req, res) => {
    try {
        const { id, remark, title } = req.body

        // 检查是否提供了ID，如果有ID则尝试更新，否则新增
        if (id) {
            // 检查记录是否存在
            const [existingRecord] = await db.query('SELECT * FROM el_repo WHERE id = ?', [id])

            if (existingRecord.length > 0) {
                // 更新现有记录
                const updateTime = new Date()
                await db.query(
                    'UPDATE el_repo SET remark = ?, title = ?, update_time = ? WHERE id = ?',
                    [remark, title, updateTime, id]
                )
                return res.json({ "msg": "更新成功！", "code": 0, "success": true })
            }
        }

        // 新增记录（如果没有提供ID或ID不存在）
        const newId = id || generate19DigitId()
        const createTime = new Date()
        const updateTime = new Date()

        await db.query(
            'INSERT INTO el_repo (id, remark, title, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
            [newId, remark, title, createTime, updateTime]
        )

        // 检查是否已经存在关联记录
        const [existingExamRepo] = await db.query('SELECT * FROM el_exam_repo WHERE repo_id = ?', [newId])

        if (existingExamRepo.length === 0) {
            const examRepoId = generate19DigitId()
            await db.query('INSERT INTO el_exam_repo (id, exam_id, repo_id) VALUES (?, ?, ?)',
                [examRepoId, 0, newId])
        }
        return res.json({ "msg": "操作成功！", "code": 0, "success": true })
    } catch (error) {
        console.log(error)
        return res.status(500).json({
            msg: "操作失败！",
            code: 1,
            data: null
        })
    }
})

module.exports = router